using System;
using System.IO;
using System.Text.RegularExpressions;

using ObjectRelationalMapping.Helper;
using ObjectRelationalMapping.Model;

namespace ObjectRelationalMapping
{
    internal static partial class Output
    {
        internal static class Database
        {
            public static void Execute ( )
            {
                if ( Common.ExecuteGeneratedSql )
                {
                    Console.Write ( "Executing the database queries..." );
                    int numberOfDatabaseQueries = 0;

                    foreach ( Entity entity in Common.EntityCollection )
                    {
                        foreach ( string databaseQuery
                            in Regex.Split ( entity.DatabaseTemplate, "(\r\nGO)" ) )
                        {
                            string formattedDatabaseQuery =
                                Regex.Replace ( databaseQuery, "(\r\nGO)", "" );
                            if ( formattedDatabaseQuery != string.Empty
                                & formattedDatabaseQuery != "\r\n\r\n" )
                            {
                                Sql.ExecuteNonQuery ( formattedDatabaseQuery );
                                ++numberOfDatabaseQueries;
                            }
                        }
                    }

                    Console.WriteLine (
                        "and {0} database queries were executed.",
                        numberOfDatabaseQueries );
                }
                else
                {
                    Console.WriteLine ( "Database queries were not executed." );
                }
            }

            internal static void Write ( )
            {
                if ( Common.EntityCollection.Count > 0 )
                {
                    Console.Write ( "Writing the database files..." );
                    int numberOfDatabaseFiles = 0;

                    string fileName;
                    StreamWriter fileWriter;

                    foreach ( Entity entity in Common.EntityCollection )
                    {
                        fileName =
                            Common.ProjectDirectoryForDatabaseObjects
                                + entity.Name + ".sql";
                        fileWriter = new StreamWriter ( fileName );
                        fileWriter.WriteLine ( entity.DatabaseTemplate );
                        fileWriter.Close ();

                        ++numberOfDatabaseFiles;
                    }

                    Console.WriteLine (
                        "and {0} database files were written.",
                        numberOfDatabaseFiles );
                }
            }
        }
    }
}